"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.restoreSvgs = void 0;
const templates_1 = require("./templates");
const tools_1 = require("./tools");
const fs = require("fs");
const path = require("path");
function restoreSvgs(options) {
    options.outputValue = options.outputValue || "/dist";
    const { inputValue, restore } = options;
    if (typeof inputValue !== "string") {
        throw new Error("input must be a string");
    }
    if (!inputValue.endsWith(".js")) {
        throw new Error("input must be a .js file");
    }
    const restoreSymbols = typeof restore === "string" ? restore.split(",").filter(Boolean) : [];
    const inputPathList = (inputValue || "").split("/").filter(Boolean);
    const inputPath = path.join(process.cwd(), ...inputPathList);
    if (!fs.existsSync(inputPath) || !fs.statSync(inputPath).isFile()) {
        throw new Error(`Input path ${inputPath} does not exist or is not a file`);
    }
    // 读取iconfont文件，生成svg文件内容
    const { svgList } = (0, tools_1.getIconfontContent)(inputPath);
    // 输出文件
    outputSvgs(svgList, restoreSymbols, options);
}
exports.restoreSvgs = restoreSvgs;
// 输出svg文件到指定目录
function outputSvgs(svgList, restoreSymbols, options) {
    const { outputValue } = options;
    const outputPathList = outputValue?.split("/").filter(Boolean) || [];
    const outputPath = path.join(process.cwd(), ...outputPathList);
    // 生成输出目录
    (0, tools_1.checkAndMakeDirPath)(outputPath);
    if (Array.isArray(svgList) && svgList.length) {
        // 所有的svgId
        const allSvgIds = svgList.map((svg) => svg.name);
        const restoreMap = (restoreSymbols.length > 0 ? restoreSymbols : allSvgIds).reduce((p, c) => {
            p[c] = true;
            return p;
        }, {});
        // 最终要恢复的svg文件
        const resultSvgList = svgList.filter((item) => restoreMap[item.name]);
        resultSvgList.forEach((svg) => {
            const { content, name, viewBox } = svg;
            const svgPath = path.join(outputPath, `${name}.svg`);
            fs.writeFileSync(svgPath, (0, templates_1.generateSvgContent)(content, viewBox));
        });
        // 生成hmtl预览
        if (resultSvgList.length) {
            fs.writeFileSync(path.join(outputPath, "index.html"), (0, templates_1.generateSvgsHtmlContent)(resultSvgList.map((item) => item.name)));
        }
    }
}
